package com.example.mvvm.pokemon.ui.list

import android.util.Log
import androidx.lifecycle.LifecycleOwner
import com.atom.module.mvvm.base.AbstractBaseViewModel
import com.atom.module.mvvm.base.IModel
import com.atom.module.mvvm.base.AbstractViewModel
import com.atom.module.mvvm.base.EmptyModel
import com.atom.module.mvvm.extren.isYes
import com.atom.module.mvvm.livedata.SingleLiveData
import com.example.mvvm.pokemon.net.ApiService
import com.example.mvvm.pokemon.net.BaseResponse
import com.example.mvvm.pokemon.net.NetHelper
import com.example.mvvm.pokemon.net.NewsCard
import retrofit2.Call
import retrofit2.Response
import timber.log.Timber

class ListViewModel : AbstractBaseViewModel<IModel>(EmptyModel) {

    val listdata = object : SingleLiveData<NewsCard>() {}

    lateinit var newsApiService: ApiService

    val callback = object : retrofit2.Callback<BaseResponse<NewsCard>> {
        override fun onResponse(
            call: Call<BaseResponse<NewsCard>>,
            response: Response<BaseResponse<NewsCard>>
        ) {
            response.isSuccessful.isYes {
                response.body()?.also {
                    Log.e("ListViewModel", "${it.reason} ${it.error_code}")
                    it.result?.also { card ->
                        listdata.post(card)
                    }
                }
            }
        }

        override fun onFailure(call: Call<BaseResponse<NewsCard>>, t: Throwable) {
            Timber.e(t)
        }
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        val defaultClient = NetHelper.defaultClient()
        val createRetrofit = NetHelper.createRetrofit("http://v.juhe.cn/", defaultClient)
        newsApiService = createRetrofit.create(ApiService::class.java)
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        newsApiService.getNews().enqueue(callback)
    }

    fun loadMoreNewsData(page:Int , page_size : Int = 30) {
        newsApiService.getNews(page = page , page_size = page_size).enqueue(callback)
    }
}